<template>
	<view class="container">

		<!-- 聊天内容区域 -->
		<scroll-view scroll-y="true" class="chat-container" scroll-with-animation :scroll-top="scrollTop"
			@scroll="onScroll" id="chatScroll">
			<view class="chat-welcome">
				<view class="welcome-title">AI医疗助手</view>
				<view class="welcome-subtitle">您的24小时健康顾问</view>
				<view class="welcome-desc">请描述您的症状，AI将为您提供初步建议</view>
				<view class="welcome-tips">
					<view class="tip-item">
						<!-- <text class="tip-icon">&#xe665;</text> -->
						<text class="tip-text">AI诊断仅供参考，严重症状请及时就医</text>
					</view>
					<view class="tip-item">
						<!-- <text class="tip-icon">&#xe665;</text> -->
						<text class="tip-text">您的信息将严格保密</text>
					</view>
				</view>
			</view>

			<view class="chat-list">
				<view class="chat-item" v-for="(msg, index) in chatMessages" :key="index"
					:class="{ 'user-message': msg.type === 'user', 'ai-message': msg.type === 'ai' }">
					<view class="avatar">
						<image :src="msg.type === 'user' ? '/static/index/yuyue.png' : '/static/index/yuyue.png'"
							mode="aspectFill"></image>
					</view>
					<view class="message-content">
						<view class="message-bubble">{{ msg.content }}</view>
						<view class="message-time">{{ msg.time }}</view>
					</view>
				</view>
			</view>

			<view class="loading-message" v-if="isAiTyping">
				<view class="avatar">
					<image src="/static/index/yuyue.png" mode="aspectFill"></image>
				</view>
				<view class="message-content">
					<view class="message-bubble typing">
						<text class="dot"></text>
						<text class="dot"></text>
						<text class="dot"></text>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 常见问题推荐 -->
		<scroll-view scroll-x="true" class="quick-questions" v-if="chatMessages.length === 0">
			<view class="question-item" v-for="(q, index) in commonQuestions" :key="index" @click="askQuestion(q)">
				{{ q }}
			</view>
		</scroll-view>

		<!-- 底部输入区域 -->
		<view class="input-container">
			<view class="input-wrapper">
				<textarea class="input-field" v-model="userInput" placeholder="请描述您的症状..." :disabled="isAiTyping"
					auto-height cursor-spacing="20" maxlength="200" @input="adjustTextareaHeight"
					@confirm="sendMessage"></textarea>
				<view class="send-btn" @click="sendMessage" :class="{ disabled: isAiTyping || !userInput.trim() }">
					发送
				</view>
			</view>

			<!-- <view class="func-btns">
				<view class="func-btn" @click="uploadImage">
					<text class="iconfont">&#xe665;</text>
					<text>上传图片</text>
				</view>
				<view class="func-btn" @click="recordVoice">
					<text class="iconfont">&#xe665;</text>
					<text>语音输入</text>
				</view>
				<view class="func-btn" @click="showSymptomList">
					<text class="iconfont">&#xe665;</text>
					<text>症状清单</text>
				</view>
			</view> -->
		</view>

		<!-- 底部预约按钮 -->
		<!-- <view class="consult-btn-container" v-if="showConsultBtn">
			<button class="consult-doctor-btn" @click="consultRealDoctor">咨询真人医生</button>
		</view> -->
	</view>
</template>

<script>
	export default {
		data() {
			return {
				userInput: '',
				chatMessages: [],
				isAiTyping: false,
				scrollTop: 0,
				showConsultBtn: false,
				textareaHeight: 70,
				commonQuestions: [
					"头痛是什么原因？",
					"感冒发烧怎么办？",
					"胃痛应该如何缓解？",
					"咳嗽有痰怎么治疗？",
					"眼睛干涩是什么原因？"
				]
			}
		},
		methods: {
			goBack() {
				uni.navigateBack();
			},
			sendMessage() {
				if (this.isAiTyping || !this.userInput.trim()) return;

				const userMsg = {
					type: 'user',
					content: this.userInput.trim(),
					time: this.formatTime(new Date())
				};

				this.chatMessages.push(userMsg);
				this.userInput = '';
				this.textareaHeight = 70;

				// 滚动到底部
				this.$nextTick(() => {
					this.scrollToBottom();
				});
				// 调用星火API
				this.callSparkAPI(userMsg.content);
			},

			callSparkAPI(userInput) {
				this.isAiTyping = true;

				// 构建API请求数据
				const requestData = {
					model: "4.0Ultra",
					messages: [{
						role: "user",
						content: userInput
					}]
				};

				// 如果是多轮对话，需要将历史消息也加入
				if (this.chatMessages.length > 2) {
					requestData.messages = [];

					// 获取最近的几条消息，构建对话历史
					// 这里限制了历史消息数量，避免tokens过多
					const historyLimit = Math.min(this.chatMessages.length - 1, 10);
					for (let i = this.chatMessages.length - 1 - historyLimit; i < this.chatMessages.length; i++) {
						const msg = this.chatMessages[i];
						requestData.messages.push({
							role: msg.type === 'user' ? 'user' : 'assistant',
							content: msg.content
						});
					}
				}
				uni.request({
					url: 'https://spark-api-open.xf-yun.com/v1/chat/completions',
					method: 'POST',
					data: requestData,
					header: {
						'Content-Type': 'application/json',
						'Authorization': 'Bearer EVLZswPnFzQiNzOkWgfy:kYipJGaozbPtsqTYNkAl'
					},
					success: (res) => {
						if (res.data && res.data.code === 0 && res.data.choices && res.data.choices.length >
							0) {
							const aiResponse = res.data.choices[0].message.content;

							const aiMsg = {
								type: 'ai',
								content: aiResponse,
								time: this.formatTime(new Date())
							};

							this.chatMessages.push(aiMsg);

							// 显示咨询真人医生按钮
							if (this.chatMessages.length >= 4) {
								this.showConsultBtn = true;
							}
						} else {
							// API请求失败或返回错误
							const errorMsg = {
								type: 'ai',
								content: "很抱歉，我暂时无法回答您的问题，请稍后再试。",
								time: this.formatTime(new Date())
							};
							this.chatMessages.push(errorMsg);

							console.error('API响应错误:', res.data);
						}
					},
					fail: (err) => {
						// 网络请求失败
						const errorMsg = {
							type: 'ai',
							content: "网络连接出错，请检查您的网络设置后重试。",
							time: this.formatTime(new Date())
						};
						this.chatMessages.push(errorMsg);

						console.error('请求失败:', err);
					},
					complete: () => {
						this.isAiTyping = false;

						// 滚动到底部
						this.$nextTick(() => {
							this.scrollToBottom();
						});
					}
				});
			},
			askQuestion(question) {
				this.userInput = question;
				this.sendMessage();
			},
			formatTime(date) {
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				return `${hours}:${minutes}`;
			},
			scrollToBottom() {
				const query = uni.createSelectorQuery().in(this);
				query.select('#chatScroll').boundingClientRect();
				query.selectAll('.chat-item').boundingClientRect();
				query.exec((res) => {
					if (res[0] && res[1] && res[1].length > 0) {
						const scrollHeight = res[1].reduce((total, item) => total + item.height, 0);
						this.scrollTop = scrollHeight;
					}
				});
			},
			onScroll(e) {
				this.scrollTop = e.detail.scrollTop;
			},
			adjustTextareaHeight(e) {
				// 根据输入内容调整输入框高度，最大高度限制
				const lineHeight = 30;
				const minHeight = 70;
				const maxHeight = 150;

				const lines = this.userInput.split('\n').length;
				const calculatedHeight = Math.min(Math.max(minHeight, lineHeight * lines), maxHeight);

				this.textareaHeight = calculatedHeight;
			},
			uploadImage() {
				uni.showToast({
					title: '图片上传功能开发中',
					icon: 'none'
				});
			},
			recordVoice() {
				uni.showToast({
					title: '语音输入功能开发中',
					icon: 'none'
				});
			},
			showSymptomList() {
				uni.showToast({
					title: '症状清单功能开发中',
					icon: 'none'
				});
			},
			consultRealDoctor() {
				uni.navigateTo({
					url: '/pages/doctor/search'
				});
			}
		}
	}
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f7fa;
	}

	.header {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		height: 90rpx;
		background-color: #ffffff;
		padding: 0 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.back-icon {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		font-weight: 500;
		color: #333333;
	}

	.placeholder {
		width: 60rpx;
	}

	.chat-container {
		flex: 1;
		padding: 30rpx;
		box-sizing: border-box;
	}

	.chat-welcome {
		background-color: #ffffff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
	}

	.welcome-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 10rpx;
	}

	.welcome-subtitle {
		font-size: 28rpx;
		color: #666666;
		margin-bottom: 20rpx;
	}

	.welcome-desc {
		font-size: 30rpx;
		color: #333333;
		margin-bottom: 30rpx;
	}

	.welcome-tips {
		background-color: #f7f9fc;
		border-radius: 8rpx;
		padding: 20rpx;
	}

	.tip-item {
		display: flex;
		flex-direction: row;
		align-items: flex-start;
		margin-bottom: 10rpx;
	}

	.tip-icon {
		font-size: 28rpx;
		color: #2b85ff;
		margin-right: 10rpx;
	}

	.tip-text {
		font-size: 26rpx;
		color: #666666;
		flex: 1;
	}

	.chat-list {
		padding-bottom: 30rpx;
	}

	.chat-item {
		display: flex;
		margin-bottom: 30rpx;
	}

	.user-message {
		flex-direction: row-reverse;
	}

	.ai-message {
		flex-direction: row;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		overflow: hidden;
		flex-shrink: 0;
	}

	.avatar image {
		width: 100%;
		height: 100%;
	}

	.message-content {
		max-width: 70%;
		margin: 0 20rpx;
	}

	.user-message .message-content {
		align-items: flex-end;
	}

	.message-bubble {
		padding: 20rpx 24rpx;
		border-radius: 18rpx;
		font-size: 30rpx;
		margin-bottom: 10rpx;
		word-wrap: break-word;
		line-height: 1.4;
	}

	.user-message .message-bubble {
		background-color: #2b85ff;
		color: #ffffff;
		border-top-right-radius: 4rpx;
	}

	.ai-message .message-bubble {
		background-color: #ffffff;
		color: #333333;
		border-top-left-radius: 4rpx;
	}

	.message-time {
		font-size: 24rpx;
		color: #999999;
	}

	.user-message .message-time {
		text-align: right;
	}

	.loading-message {
		display: flex;
		flex-direction: row;
		margin-bottom: 30rpx;
	}

	.typing {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.dot {
		display: inline-block;
		width: 10rpx;
		height: 10rpx;
		border-radius: 50%;
		background-color: #999999;
		margin: 0 4rpx;
		animation: typing 1.5s infinite ease-in-out;
	}

	.dot:nth-child(2) {
		animation-delay: 0.2s;
	}

	.dot:nth-child(3) {
		animation-delay: 0.4s;
	}

	@keyframes typing {

		0%,
		100% {
			transform: translateY(0);
		}

		50% {
			transform: translateY(-10rpx);
		}
	}

	.quick-questions {
		background-color: #ffffff;
		padding: 20rpx;
		white-space: nowrap;
		border-top: 1rpx solid #eeeeee;
	}

	.question-item {
		display: inline-block;
		padding: 15rpx 30rpx;
		background-color: #f7f9fc;
		border-radius: 30rpx;
		font-size: 26rpx;
		color: #333333;
		margin-right: 15rpx;
	}

	.input-container {
		background-color: #ffffff;
		padding: 20rpx;
		border-top: 1rpx solid #eeeeee;
	}

	.input-wrapper {
		display: flex;
		align-items: flex-end;
		border: 1rpx solid #eeeeee;
		border-radius: 40rpx;
		padding: 10rpx 10rpx 10rpx 30rpx;
		background-color: #ffffff;
	}

	.input-field {
		flex: 1;
		font-size: 30rpx;
		min-height: 70rpx;
		max-height: 150rpx;
		line-height: 1.5;
	}

	.send-btn {
		width: 120rpx;
		height: 64rpx;
		line-height: 64rpx;
		text-align: center;
		background-color: #2b85ff;
		color: #ffffff;
		border-radius: 32rpx;
		font-size: 28rpx;
	}

	.send-btn.disabled {
		background-color: #cccccc;
	}

	.func-btns {
		display: flex;
		flex-direction: row;
		margin-top: 20rpx;
	}

	.func-btn {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-right: 40rpx;
	}

	.func-btn text {
		font-size: 24rpx;
		color: #666666;
		margin-top: 5rpx;
	}

	.consult-btn-container {
		padding: 20rpx;
		background-color: #ffffff;
		border-top: 1rpx solid #eeeeee;
	}

	.consult-doctor-btn {
		height: 90rpx;
		line-height: 90rpx;
		text-align: center;
		border-radius: 45rpx;
		background-color: #ffcc33;
		color: #333333;
		font-size: 32rpx;
		font-weight: 500;
	}
</style>